<template>
  <div class="custom-tree-container">
    <p>Using scoped slot</p>
    <el-tree
      style="max-width: 600px"
      :data="dataSource"
      show-checkbox
      node-key="id"
      default-expand-all
      :expand-on-click-node="false"
      :props="{ class: customNodeClass }"
    >
      <template #default="{ node, data }">
        <div class="custom-tree-node">
          <span>{{ node.label }}</span>
        </div>
      </template>
    </el-tree>
  </div>


  <div id="date" class="semi_arc">
    <div class="semi_arc_2 e4_1">
      <div class="counterspin4"></div>
    </div>
    <div ref="chartDom" class="chart-dom"></div>
  </div>


  <el-button type="primary" @click="downPdf">下载pdf</el-button>
</template>

<script lang="ts" setup>
import {onMounted, ref} from 'vue'
import type Node from 'element-plus/es/components/tree/src/model/node'
import type {TreeNodeData} from 'element-plus/es/components/tree/src/tree.type'
import * as echarts from 'echarts'
import {PDFDocument, rgb} from 'pdf-lib';
import pdf from '@/assets/dyTemplate.pdf'
import fontkit from '@pdf-lib/fontkit'

interface Tree {
  id: number
  label: string
  children?: Tree[]
  disabled: boolean
}


const customNodeClass = ({isHidden}: any, node: any) =>
  isHidden ? 'is-hidden' : ''

const dataSource = ref([
  {
    id: 1,
    label: 'Level one 1',
    children: [
      {
        id: 4,
        label: 'Level two 1-1',
        children: [
          {
            id: 9,
            label: 'Level three 1-1-1',
            isHidden: true,
          },
          {
            id: 10,
            label: 'Level three 1-1-2',
            isHidden: true,
          },
        ],
      },
    ],
  },
  {
    id: 2,
    label: 'Level one 2',
    children: [
      {
        id: 5,
        label: 'Level two 2-1',
      },
      {
        id: 6,
        label: 'Level two 2-2',
      },
    ],
  },
  {
    id: 3,
    label: 'Level one 3',
    children: [
      {
        id: 7,
        label: 'Level two 3-1',
      },
      {
        id: 8,
        label: 'Level two 3-2',
      },
    ],
  },
])

const chartDom = ref<HTMLElement | null>(null)
// 在 onMounted 中或其他合适时机初始化图表
onMounted(() => {
  if (chartDom.value) {
    const myChart = echarts.init(chartDom.value)
    myChart.setOption({
      "title": [{
        "text": "78%",
        "left": "center",
        "top": "center",
        "textStyle": {
          "fontSize": 28,
          "color": "#fff",
          "fontFamily": "DINAlternate-Bold, DINAlternate",
          "fontWeight": "normal"
        }
      }],
      "series": [
        {
          "type": "pie",
          "radius": ["50%", "70%"],
          "avoidLabelOverlap": true,
          "label": {"show": false},
          "labelLine": {"show": false},
          "silent": false,
          "data": [
            {"itemStyle": {"color": "#c0c0c0"}, "value": 22, "name": "1"},
            {
              "itemStyle": {
                "color": {
                  type: 'linear',
                  x: 0,
                  y: 0,
                  x2: 0,
                  y2: 1,
                  colorStops: [
                    {
                      offset: 0, color: '#a098fb' // 0% 处的颜色
                    },
                    {
                      offset: 0.3, color: '#4888f6' // 100% 处的颜色
                    },
                    {
                      offset: 0.7, color: '#10d0dd' // 100% 处的颜色
                    },
                    {
                      offset: 1, color: '#5779f4' // 100% 处的颜色
                    }
                  ],
                  global: false // 缺省为 false
                }
              },
              "value": 78,
              "name": "2"
            }

          ]
        },
        {
          "type": "pie",
          "radius": ["38%", "43%"],
          "avoidLabelOverlap": true,
          "label": {"show": false},
          "labelLine": {"show": false},
          "silent": true,
          "data": [
            {
              "itemStyle": {"color": "#c0c0c0"},
              "value": 22,
              "name": "1"
            },
            {
              "itemStyle": {"color": "#4ebfff"},
              "value": 78,
              "name": "2"
            }
          ]
        }, {
          "type": "pie",
          "startAngle": 80,
          "radius": ["38%"],
          "hoverAnimation": false,
          "animation": false,
          "center": ["50%", "50%"],
          "data": [100],
          "itemStyle": {"color": "rgba(2, 141, 255, 0)"}
        }]
    })
  }
})


const downPdf = async () => {
  const url = pdf; // 替换为你的 PDF 文件路径
  const existingPdfBytes = await fetch(url).then(res => res.arrayBuffer());
  const pdfDoc = await PDFDocument.load(existingPdfBytes);

  // 注册 fontkit 支持字体解析
  pdfDoc.registerFontkit(fontkit);
  // 加载中文字体文件（确保路径正确）
  const fontUrl = '/fonts/AlibabaPuHuiTi-3-45-Light.ttf';
  const fontBytes = await fetch(fontUrl).then(res => res.arrayBuffer());

  // 嵌入字体
  const chineseFont = await pdfDoc.embedFont(fontBytes);


  // 对象包含需要更新的字段值
  const data = {
    gdbh: '我是',
    // ywlb: data.ywlb || '/' ,
    // yyqy: data.yyqy || '/',
    // yhbh: data.yhbh || '/',
    // yhmc: data.yhmc || '/',
    // yddz: data.yddz || '/',
    // dydj: data.dydj || '/',
    // ydlb: data.ydlb || '/',
    // ybzrl:data.ybrl || '/',
    // bzrl: data.bzrl || '/',
    // hjrl: data.hjrl || '/',
    // gdxl: faxx.gdxl || '/',
    // pbmc: faxx.pbmc || '/',
    // jlfs: faxx.jlfs || '/',
    // hjrl: faxx.hjrl || '/',
    // ctpb: faxx.ctpb || '/',
    // djlb: faxx.djlb || '/',
    // zxdj: faxx.zxdj || '/'
  };


  const pages = pdfDoc.getPages();
  console.log(pdfDoc.getPages())
  const targetPage = pages[0]; // 修改为你的目标页
  const {height} = targetPage.getSize();
  console.log(height)
  for (const fieldName of Object.keys(data)) {
    const value = data[fieldName];

    // 示例坐标（可以根据字段名动态设置不同位置）
    const x = 170;
    const y = height - 185;

    // 清除旧内容（白色矩形遮盖）
    targetPage.drawRectangle({
      x,
      y: y - 3,
      width: 50,
      height: 14,
      color: rgb(1, 1, 1),
      // color: rgb(0.3, 0.3, 0.3),
    });

    // 绘制新文本
    targetPage.drawText(value, {
      x,
      y,
      size: 12,
      color: rgb(0, 0, 0),
      font: chineseFont,
    });
  }

  const pdfBytes = await pdfDoc.save();

  // 创建 Blob 对象并触发下载
  const blob = new Blob([pdfBytes], {type: 'application/pdf'});
  const link = document.createElement('a');
  link.href = URL.createObjectURL(blob);
  link.download = 'modified-file.pdf'; // 设置下载文件名
  link.click();
}

</script>

<style>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}

.is-hidden {
  display: none;
}

.chart-dom {
  width: 300px;
  height: 300px;
}

.semi_arc {
  width: 312px;
  height: 312px;
  border: 6px solid #028dff;
  background: rgba(2, 141, 255, 0.2);
  -moz-border-radius: 50%;
  -webkit-border-radius: 50%;
  border-radius: 50%;
  transform: rotateZ(0deg);
  transition: box-shadow 3s ease;
  text-align: center;
}

.semi_arc:hover {
  box-shadow: 0 0 30px rgba(22, 141, 255, 0.8);
  transition: .3s;
}

.semi_arc_2 {
  content: "";
  position: absolute;
  width: 94%;
  height: 94%;
  left: 3%;
  top: 3%;
  border: 5px solid #4486f7;
  -moz-border-radius: 50%;
  -webkit-border-radius: 50%;
  border-radius: 50%;
  -moz-box-sizing: border-box;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  animation: rotate 4s linear infinite;
  text-align: center;
  line-height: 129px;
  border-color: rgba(2, 141, 255, 0.3);
  border-left: 5px solid transparent;
  border-right: 5px solid transparent;
}

.semi_arc_2:after {
  content: "";
  position: absolute;
  width: 94%;
  height: 94%;
  left: 3%;
  top: 3%;
  border: 4px solid #4486f7;
  -moz-border-radius: 50%;
  -webkit-border-radius: 50%;
  border-radius: 50%;
  -moz-box-sizing: border-box;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  animation: rotate_anti 2s linear infinite;
  border-color: rgba(2, 141, 255, 0.6);
  border-top: 4px solid transparent;
  border-bottom: 4px solid transparent;
}

.counterspin4 {
  animation: rotate_anti 4s linear infinite
}

@keyframes rotate {
  0% {
    transform: rotateZ(0deg)
  }

  100% {
    transform: rotateZ(360deg)
  }
}

@keyframes rotate_anti {
  0% {
    transform: rotateZ(360deg)
  }

  100% {
    transform: rotateZ(0deg)
  }
}

</style>
